
<template>
  <div style="margin-top: 60px;margin-left:80px;border: 0px solid red;">
    <el-form style="margin-left: -40px" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="字段：" prop="key">
        <el-select v-model="ruleForm.key" style="width: 160px;float: left" placeholder="请选择字段">
          <el-option label="名称" value="name"></el-option>
          <el-option label="电话" value="telephone"></el-option>
        </el-select>
      </el-form-item>
      <div style="border: 0px solid red;width: 400px;height: 60px;position: relative;top: -64px;left: 270px">
        <el-form-item label="值：">
          <el-input v-model="ruleForm.value" placeholder="请输入关键字" style="width: 160px;"></el-input>
          <el-button type="primary" icon="el-icon-search" style="position: relative;left: 10px;" @click="submitForm('ruleForm')">搜索</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table
        :data="tableData"
        border
        stripe
        style="width: 1161px;position: relative;top:-30px">
      <el-table-column
          fixed
          prop="id"
          label="ID">
      </el-table-column>
      <el-table-column
          prop="buildingName"
          label="楼宇">
      </el-table-column>
      <el-table-column
          prop="name"
          label="名称">
        <template slot-scope="scope">
          <el-button type="text" @click="openDialog(scope.row)">【{{ scope.row.name }}】</el-button>
        </template>
      </el-table-column>
      <el-table-column
          prop="type"
          label="几人间">
      </el-table-column>
      <el-table-column
          prop="available"
          label="空余床位">
      </el-table-column>
      <el-table-column
          prop="telephone"
          label="电话">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="edit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 20px;float: right"
                   background
                   layout="prev, pager, next"
                   :page-size="pageSize"
                   :total="total"
                   :current-page.sync="currentPage"
                   @current-change="page">
    </el-pagination>

    <!-- Dialog 弹窗 -->
    <el-dialog
        title="宿舍详情"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose">

      <!-- 搜索框 -->
      <el-form style="margin-left: -40px" :model="ruleStudentForm" :rules="studentRules" ref="ruleStudentForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="字段：" prop="key">
          <el-select v-model="ruleStudentForm.key" style="width: 160px;float: left" placeholder="请选择字段">
            <el-option label="学号" value="number"></el-option>
            <el-option label="姓名" value="name"></el-option>
          </el-select>
        </el-form-item>
        <div style="border: 0px solid red;width: 400px;height: 60px;position: relative;top: -64px;left: 270px">
          <el-form-item label="值：">
            <el-input v-model="ruleStudentForm.value" placeholder="请输入关键字" style="width: 160px;"></el-input>
            <el-button type="primary" icon="el-icon-search" style="position: relative;left: 10px;" @click="submitStudentForm('ruleStudentForm')">搜索</el-button>
          </el-form-item>
        </div>
      </el-form>

      <!-- 学生列表表格 -->
      <el-table :data="tableStudentData" border stripe style="width: 100%; position: relative; top: -30px">
        <el-table-column fixed prop="id" label="ID"></el-table-column>
        <el-table-column prop="dormitoryName" label="宿舍"></el-table-column>
        <el-table-column prop="number" label="学号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="gender" label="性别"></el-table-column>
        <el-table-column prop="state" label="状态"></el-table-column>
        <el-table-column prop="telephone" label="电话号码"></el-table-column>
        <el-table-column prop="createDate" label="入住时间"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </span>
    </el-dialog>



  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: null,
      tableStudentData:null,
      studentTotal:null,
      currentPage: 1,
      currentDormitoryId:null,
      pageSize: 3,
      total: null,
      ruleStudentForm:{
        key: '',  // 搜索字段（学号或姓名）
        value: '' // 搜索值（关键字）
      },
      ruleForm: {
        key: '',  // 搜索字段（学号或姓名）
        value: '' // 搜索值（关键字）
      },
      rules: {
        key: [
          { required: true, message: '请选择字段', trigger: 'change' }
        ]
      },
      studentRules: {
        key: [
          { required: true, message: '请选择字段', trigger: 'change' }
        ]
      },
      dialogVisible: false,   // 控制 Dialog 显示隐藏
      dialogData: {},         // 存储 Dialog 展示的数据
    }
  },
  methods: {
    // 搜索功能
    submitForm(formName) {
      const _this = this;
      _this.currentPage = 1; // 重置为第一页
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.ruleForm.page = _this.currentPage;
          axios.get('http://localhost:8181/dormitory/search', { params: _this.ruleForm })
              .then(function (resp) {
                _this.tableData = resp.data.data.data;
                _this.total = resp.data.data.total;
              });
        }
      });
    },
    submitStudentForm(formName){
      const _this = this;
      _this.currentPage = 1; // 重置为第一页
      _this.ruleStudentForm.page = _this.currentPage;
      _this.ruleStudentForm.size=_this.pageSize;
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await axios.get('http://localhost:8181/student/search', { params: _this.ruleStudentForm })
              .then(function (resp) {
                _this.tableStudentData = resp.data.data.data;
                _this.total = resp.data.data.total;
              });
          console.log(_this.tableStudentData)
        }
      });
    },
    // 分页功能
    page(currentPage) {
      const _this = this;
      _this.ruleForm.page = currentPage;
      if (_this.ruleForm.value === '') {
        axios.get(`http://localhost:8181/dormitory/list/${currentPage}/${_this.pageSize}`)
            .then(function (resp) {
              _this.tableData = resp.data.data.data;
              _this.total = resp.data.data.total;
            });
      } else {
        axios.get('http://localhost:8181/dormitory/search', { params: _this.ruleForm })
            .then(function (resp) {
              _this.tableStudentData = resp.data.data.data;
              _this.total = resp.data.data.total;
            });
      }
    },
    // 打开 Dialog 展示详情
    openDialog(row) {
      this.dialogData = { ...row };
      this.dialogVisible = true;
      const _this=this
      _this.currentDormitoryId=row.id;
      axios.get('http://localhost:8181/student/search',{
        params:{
          dormitoryId:_this.currentDormitoryId,
          page:_this.currentPage,
          size:10,
        }
      }).then(function (resp) {
        _this.tableStudentData = resp.data.data.data
        _this.studentTotal = resp.data.data.total
      })
    },
    // 关闭 Dialog 确认
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(() => {});
    },
    // 编辑功能
    edit(row) {
      this.$router.push(`/dormitoryUpdate?id=${row.id}`);
    },
    // 删除功能
    del(row) {
      const _this = this;
      this.$confirm(`确认删除【${row.name}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8181/dormitory/deleteById/${row.id}`)
            .then(function (resp) {
              if (resp.data.code === 0) {
                _this.$alert(`【${row.name}】已删除`, '', {
                  confirmButtonText: '确定',
                  callback: () => {
                    _this.page(_this.currentPage); // 刷新列表
                  }
                });
              }
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  // 搜索学生数据
  searchStudentData() {
    const { key, value } = this.ruleForm;
    if (key && value) {
      // 根据选择的字段和关键字筛选学生数据
      this.filteredStudentData = this.tableStudentData.filter(student => {
        return student[key] && student[key].toString().includes(value);
      });
    } else {
      // 如果没有输入关键字，显示所有数据
      this.filteredStudentData = [...this.tableStudentData];
    }
  },
  created() {
    const _this = this;
    axios.get(`http://localhost:8181/dormitory/list/1/${_this.pageSize}`)
        .then(function (resp) {
          _this.tableData = resp.data.data.data;
          _this.total = resp.data.data.total;
        });
  }
}
</script>
